console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import { generateImg } from './../../lib/zeroReportUtils.js';
import { zeroReprot, zcfzbWrite, baoBiaoDetailBack } from './zeroReprot.js';

let baseInfoCache;

window.onload = function () {
  // // 登录填写账号密码
  // if (/\/ssoserver\/login/g.test(window.location.pathname)) {
  //   window.postMessage({
  //     event: "getBaseInfo"
  //   }, "*")
  // }
  window.postMessage({
    event: 'getBaseInfo'
  }, '*');
  window.postMessage(
    {
      event: 'getZeroInfo'
    },
    '*'
  );

  // let htmlContents = document.querySelector('.sbjg-search-table');

  // // 生产图片
  // generateImg(htmlContents);
};

window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    fillInput(await transformDataByOpenWeb(data.data));
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    baseInfoCache = data.data;
    autoInputAccount(baseInfoCache.companyInfo);
  }

  if (data.event === 'getZeroInfoBack') {
    if (data.data.isOpenZeroReport) {
      let zeroInfo = data.data;
      let href = window.location.href;
      let loginIndex = 'https://etax.shanghai.chinatax.gov.cn/wszx-web/bszm/apps/views/beforeLogin/indexBefore/pageIndex.html';
      if (href.includes(loginIndex)) {
        autoInputAccount(zeroInfo.currentZeroInfo);
        // zcfzbWrite(zeroInfo.currentZeroInfo);
      } else {
        console.log(zeroInfo.currentZeroInfo);
        zeroReprot(zeroInfo.currentZeroInfo);
      }
    }
  }

  if (data.event === 'baoBiaoDetailBack') {
    baoBiaoDetailBack(data.data);
  }

  // 零申报结束返回事件
  if (data.event === 'zeroReportEnd') {
    setTimeout(() => {
      window.postMessage(
        {
          event: 'asyncTableDetailRequest'
        },
        '*'
      );
    }, 100);
  }
  if (data.event === 'asyncTableDetailRequestEnd') {
    window.postMessage(
      {
        event: 'clearZeroReport'
      },
      '*'
    );
    setTimeout(() => {
      document.querySelector('#loginOut').click();
    }, 1000);
  }

  // zeroReprot();
}, false);

function autoInputAccount({ nationalTaxNo, nationalTaxPass, nationalTaxId }) {
  let closeBtn = $('.mini-tools-close');
  Array.from(closeBtn).map(item => {
    item.click()
  })

  window.saveCookieAndLogin();

  // window.clipboardData.setData('nationalTaxNo', nationalTaxNo);
  // window.clipboardData.setData('nationalTaxPass', nationalTaxPass);

  setTimeout(() => {
    // $('#userName').onfocus()
    // $('#userName').val(nationalTaxNo);
    // $('#userName').onblur()
    // $('#passWord').onfocus()
    // $('#passWord').val(nationalTaxPass);
    // $('#passWord').onblur()
    $('#userName').parent().css('margin-bottom', '30px').append(`<div>${nationalTaxNo || nationalTaxId || ''}<div>`);
    $('#passWord').parent().css('margin-bottom', '30px').append(`<div>${nationalTaxPass}<div>`);
    // let Text1 = window.clipboardData.getData('nationalTaxNo');
    // let Text2 = window.clipboardData.getData('nationalTaxPass');

    // $('#passWord').css('display', 'inline').val(nationalTaxPass).removeAttr('onblur onfocus');
  }, 200);
}

/**
 * 调用接口获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: baseInfoCache.companyInfo.nationalTaxId, // 纳税人申报号
    nsrmc: baseInfoCache.companyInfo.companyName, // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
    outPutType: 'xml' // 填报方式
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

function fillInput({ saasData, baseInfo }) {
  let message = '';
  if (saasData.data.type === 'file') {
    message = downloadFile(saasData.data.data, baseInfo);
  } else {
    message = '不支持json方式，下载文件失败！';
  }

  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message || '下载文件成功'
    }
  }, '*');
}

/**
 * 下载文件
 * @param blob
 */
function downloadFile(blob, { taxInfo }) {
  blob = new Blob([blob], { type: 'text/xml' });
  let a = document.createElement('a');
  // 指定生成的文件名
  let name = `${taxInfo.nsrsbh}_${taxInfo.institution === '2013' ? 'ZL019' : 'ZL001'}`;
  const start = taxInfo.skssqq.replace(/-/g, '');
  const end = taxInfo.skssqz.replace(/-/g, '');
  a.download = `${name}_${start}_${end}.xml`;
  a.href = URL.createObjectURL(blob);
  document.body.appendChild(a);
  a.click();
}
